<?php
/**
 * 微信会员卡模块微站定义
 *
 * @author 橙橙同学
 * @url 
 */
defined('IN_IA') or exit('Access Denied');

load()->func('communication');

class Orange_wechatcardModuleSite extends WeModuleSite {

    //微信上传图片
    const UPLOADING = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=';
    //创建会员卡
    const CREATECARD = 'https://api.weixin.qq.com/card/create?access_token=';
    //设置开卡字段
    const ACTIVATEUSERFROM = 'https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token=';
    //跳转型一键激活 获取用户信息
    const ACTIVATETEMPINFO = 'https://api.weixin.qq.com/card/membercard/activatetempinfo/get?access_token=';
    //接口激活
    const ACTIVATE = 'https://api.weixin.qq.com/card/membercard/activate?access_token=';
    //更新会员卡
    const UPDATECARD = 'https://api.weixin.qq.com/card/update?access_token=';

    const DECRYPYCODE = 'https://api.weixin.qq.com/card/code/decrypt?access_token=';

    /**
     * @param $uniacid
     * @return array|mixed
     * @author: 橙橙同学
     * @fun:获取accessToken
     */
    protected function getAccessToken($uniacid){
        $weiObj = WeAccount::create($uniacid);
        $token = $weiObj->fetch_token();
        return $token;
    }


    /**
     *  一键跳转型激活后 code 解码
     */
    protected function decryptCode($encrypt_code)
    {
        global $_W;

        $url = self::DECRYPYCODE.$this->getAccessToken($_W['uniacid']);

        $data = array('encrypt_code' => $encrypt_code);
        $sendData = json_encode($data);
        $decryptData = $this->http_attach_post($url, $sendData);

        $retMsg = json_decode($decryptData, true);
        if (0 == $retMsg['errcode']) {
            return $retMsg['code'];
        } else {
            return false;
        }
    }


    /**
     * @param $token
     * @param $activate_ticket
     * @return mixed
     * @author: 橙橙同学
     * @fun:获取用户激活会员卡填写的信息
     */
    public function getActiveCardUserInfo($activate_ticket){
        global $_W;
        $url = self::ACTIVATETEMPINFO.$this->getAccessToken($_W['uniacid']);
        $data = array(
            "activate_ticket"=>$activate_ticket
        );
        $response = ihttp_request($url, json_encode($data));
        return $response;
    }

    /**
     * @author: 橙橙同学
     * @fun:接口激活会员卡
     */
    protected function toActiveCard($memberInfo){

        global $_W;
        //查询会员领取的会员卡信息
        /*
        $memberCardInfo = pdo_fetch("SELECT * FROM " . tablename('wechatcard_record') . " 
        WHERE `uniacid`=:uniacid and `openid`=:openid and `card_id`=:card_id ", array(':uniacid'=>$_W['uniacid'],':openid'=>$_W['openid'],':card_id'=>$memberInfo['card_id']));
        */
        //查询此会员卡信息 主要用于会员卡背景图案设置
        $cardInfo = pdo_fetch("SELECT * FROM " . tablename('wechatcard_createcard') . " 
        WHERE `uniacid`=:uniacid and `card_id`=:card_id ", array(':uniacid'=>$_W['uniacid'],':card_id'=>$memberInfo['card_id']));

        $background_pic_url = $this->doMobileWechatUploadImage($cardInfo['background_pic_url']);


        $data = array(
            'membership_number'=>$memberInfo['memberMobile'],
            'code'=>$memberInfo['code'],
            'background_pic_url'=>$background_pic_url,
        );

        $url = self::ACTIVATE.$this->getAccessToken($_W['uniacid']);
        $response = ihttp_request($url,json_encode($data));
        return json_decode($response);
    }


    /*
    * 查询CRM会员信息
    */
    protected function getCustInfoFromCRM($tel){

        return array(
            'customerUid'=>'1'.rand(1,10000),
            'name'=>'戴晨'.rand(1,10000)
        );

        $request_url = $this->hostList['crm_getCustInfo'].$this->apiSignature();
        $requestData = "&customerTel=".$tel;
        $rs = $this->http_attach_post($request_url.$requestData,NULL);
        $rsArr = json_decode($rs,true);
        /*
         * request Demo
         * Array(
                    [ret] => 200
                    [data] => Array
                        (
                            [0] => Array
                                (
                                    [customrUid] => 345541423225932707
                                    [customerUid] => 345541423225932707
                                    [categoryName] => 会员
                                    [number] => 13186184263
                                    [name] => 代彦伟
                                    [point] => 0
                                    [discount] => 100
                                    [balance] => 0
                                    [phone] => 13186184263
                                    [createdDate] => 2017-07-15 00:00:00
                                    [onAccount] => 0
                                    [enable] => 1
                                    [password] => 96E79218965EB72C92A549DD5A330112
                                    [createStoreAppIdOrAccount] => E3E505E7F461E28FAEAA27B6013661FF
                                )
                        )
                    [msg] =>
                )
         */
        if($rsArr['ret'] == 200 && count($rsArr['data']) ){
            return $rsArr['data'][0];
        }else{
            return false;
        }
    }


    /*
    * 注册crm会员
    */
    protected function regCrmCust($name,$tel){
        return true;
        $request_url = $this->hostList['crm_regCust']."&name=".$name."&phone=".$tel.$this->apiSignature();
        $rs = $this->http_attach_post($request_url,NULL);
        $rsArr = json_decode($rs,true);
        if($rsArr['ret'] == '200' && $rsArr['data'] == 'success'){
            return true;
        }else{
            return false;
        }
    }

    /*
     * 查询本地会员信息
     */
    protected function getCustInfoFromLocal($tel){
        global $_W;
        $row = pdo_fetch("SELECT * FROM " . tablename('mc_members') . " 
        WHERE `mobile`=:tel and `uniacid`=:uniacid", array(':tel'=>$tel,':uniacid'=>$_W['uniacid']));
        return empty($row) ? false : $row;
    }


    /**
     * @param int $openid
     * @param int $name
     * @param int $tel
     * @param int $customerUid
     * @param string $code
     * @return bool
     * @author:橙橙同学
     * @func:激活会员/mc_member插入信息/mc_card_members插入信息/mc_mappingfans更新UID
     */
    public function doMobileActiviteMember($openid = 0,$name = 0,$tel = 0,$customerUid = 0 ,$code = ""){

        global $_W,$_GPC;
        $openid = empty($openid) ? $_W['openid'] : $openid;
        $name = empty($name) ? $_GPC['name'] : $name;
        $tel = empty($tel) ? $_GPC['tel'] : $tel;
        //crm Uid
        $customerUid = empty($customerUid) ? $_GPC['customerUid'] : $customerUid;
        //默认会员组 商业会员
        $default_groupid = pdo_fetchcolumn('SELECT groupid FROM ' .tablename('mc_groups') . ' WHERE uniacid = :uniacid AND isdefault = 1', array(':uniacid' => $_W['uniacid']));
        //获取粉丝信息
        $fan = mc_fansinfo($_W['openid']);
        if (!empty($fan)) {
            $map_fans = $fan['tag'];
        }
        if (empty($map_fans) && isset($_SESSION['userinfo'])) {
            $map_fans = unserialize(base64_decode($_SESSION['userinfo']));
        }

        if($openid && $name && $tel && $customerUid){
            try {
                pdo_begin();
                $members_data = array(
                    'mobile' => $tel,
                    'uniacid' => $_W['uniacid'],
                    'realname' => $name,
                    'nickname' => $name,
                    'idcard' => $customerUid,
                    'createtime' => time(),
                    'groupid'=>$default_groupid,
                );

                //同步粉丝表的一些基本信息
                if(!empty($map_fans)) {
                    $members_data['nickname'] = strip_emoji($map_fans['nickname']);
                    $members_data['gender'] = $map_fans['sex'];
                    $members_data['residecity'] = $map_fans['city'] ? $map_fans['city'] . '市' : '';
                    $members_data['resideprovince'] = $map_fans['province'] ? $map_fans['province'] . '省' : '';
                    $members_data['nationality'] = $map_fans['country'];
                    $members_data['avatar'] = rtrim($map_fans['headimgurl'], '0') . 132;
                }

                pdo_insert('mc_members', $members_data);
                $uid = pdo_insertid();

                if(!$uid){
                    throw new Exception('插入mc_members数据表失败');
                }

                $card_data = array(
                    'uid' => $uid,
                    'openid' => $openid,
                    'uniacid' => $_W['uniacid'],
                    'cardsn' => $tel,
                    'createtime' => time(),
                    'code' => $code,
                    'status'=>1
                );

                $card_insert_id = pdo_insert('mc_card_members',$card_data);

                if(!$card_insert_id){
                    throw new Exception('插入mc_card_members数据表失败');
                }

                if (!empty($fan) && !empty($fan['fanid'])) {
                    $fan_update_id = pdo_update('mc_mapping_fans', array('uid'=>$uid), array('fanid'=>$fan['fanid']));
                    if(!$fan_update_id){
                        throw new Exception('更新mc_mapping_fans数据表失败');
                    }
                }
                pdo_commit();
            }catch (Exception $e){
                pdo_rollback();
                echo $e->getMessage();
//                logs("|激活失败|插入数据错误,错误信息：".$e->getMessage(),'member');
                return false;
            }
            return true;
        }else{
//            logs("|激活失败|输入信息为空，openid:".$openid."  name:".$name."  tel:".$tel."  customerUid:".$customerUid,'member');
            return false;
        }
    }

    /**
     * @author:橙橙同学
     * @func:公共激活会员信息
     */
    public function commonActiveMember($openid,$memberName,$memberMobile,$crm,$code,$memberInfo){
        //获取
        $local = $this->getCustInfoFromLocal($memberMobile);
        if($local){
            message('对不起，您输入的信息已存在，请核实后再次尝试激活', 'error');
        }else{
            $rs = $this->doMobileActiviteMember($openid,$memberName,$memberMobile,$crm['customerUid'],$code);
            if($rs){
                $response = $this->toActiveCard($memberInfo);
                if($response['errcode'] == 0) {
                    header("Location: http://vkwechat.mebaby.cn/app/index.php?i=2&c=entry&do=entry&m=orange_member");
                }else{
                    message('对不起，卡券激活失败', referer(), 'error');
                }
            }else{
                message('激活会员卡失败，请核对信息后再次尝试激活！', referer(), 'error');
            }
        }
    }

    /**
     * @author: 橙橙同学
     * @fun:激活会员卡 跳转入口
     */
    public function doMobileActiveCard(){
        global $_W,$_GPC;
        $openid = $_GPC['openid'];
        $activate_ticket = $_GPC['activate_ticket'];
        $card_id = $_GPC['card_id'];
        $outer_str = $_GPC['outer_str'];
        $code = $this->decryptCode($_GPC['encrypt_code']);
        //获取会员一键跳转填写的信息
        $userinfo = $this->getActiveCardUserInfo($activate_ticket);
        $userArr = json_decode($userinfo['content'],true);

        if(isset($userArr['info']['common_field_list']) && !empty($userArr['info']['common_field_list'])){
            //获取会员填写的信息
            foreach ($userArr['info']['common_field_list'] as $value){
                $userInfoFormat[$value['name']] = $value['value'];
            }
            $memberName = $userInfoFormat['USER_FORM_INFO_FLAG_NAME'];
            $memberMobile = $userInfoFormat['USER_FORM_INFO_FLAG_MOBILE'];
            //传递必要信息进行接口激活
            $memberInfo = array('memberName'=>$memberName,'memberMobile'=>$memberMobile,'card_id'=>$card_id,'openid'=>$openid,'code'=>$code);

            if($memberName && $memberMobile){
                //获取crm用户信息
                $crm = $this->getCustInfoFromCRM($memberMobile);
                if($crm){
                    $this->commonActiveMember($openid,$memberName,$memberMobile,$crm,$code,$memberInfo);
                }else{
                    $regRs = $this->regCrmCust($memberName,$memberMobile);
                    if($regRs){
                        $crm = $this->getCustInfoFromCRM($memberMobile);
                        $this->commonActiveMember($openid,$memberName,$memberMobile,$crm,$code,$memberInfo);
                    }else{
                        message('对不起，CRM服务异常，请再试一次！', referer(), 'error');
                    }
                }
            }else{
                message('对不起，获取注册信息异常，请再试一次！', referer(), 'error');
            }
        }else{
            message('非法信息！', referer(), 'error');
        }
    }

    /**
     * @param $data
     * @return bool
     * @author: 橙橙同学
     * @fun:保存会员卡创建日志
     */
    public function saveWechatCardCreateCard($data){
        $res = pdo_insert('wechatcard_createcard', $data);
        if($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param $data
     * @param $where
     * @return bool
     * @author: 橙橙同学
     * @fun:更新会员卡日志
     */
    public function updateWechatCardCreateCard($data,$where){
        $res = pdo_update('wechatcard_createcard', $data,$where);
        if($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param $rest
     * @param $token
     * @return mixed
     * @author: 橙橙同学
     * @fun:设置会员卡激活字段
     */
    public function wechatCardActivateUserform($rest,$card_id){
        global $_W;
        // 如果设置自动激活
        // 手机号 姓名 设置字段
        $listcr = '{
                          "card_id":"'.$card_id.'",
                          "required_form":{
                                  "common_field_id_list": [
                                           "USER_FORM_INFO_FLAG_MOBILE",
                                           "USER_FORM_INFO_FLAG_NAME"
                                  ]
                          }
                }';
        //设置开卡字段
        $url = self::ACTIVATEUSERFROM.$this->getAccessToken($_W['uniacid']);
        $rest= $this->http_attach_post($url, $listcr);
        $actErrCode=json_decode($rest)->errcode;
        $actErrMsg=json_decode($rest)->errmsg;
        if($actErrCode != 0){
            return $actErrMsg;
        }else{
            return 0;
        }
    }
    /**
     * @param string $uploadImg
     * @return bool
     * @author: 橙橙同学
     * @fun:微信图片上传
     */
    public function doMobileWechatUploadImage($uploadImg =''){
        if($uploadImg == ''){
            return false;
        }
        global $_W;
        load()->func('communication');
        $token = $this->getAccessToken($_W['uniacid']);
        $url = self::UPLOADING.$token;

        $data = array(
            'media' => '@' . ATTACHMENT_ROOT . $uploadImg,
        );
        $response = ihttp_request($url, $data);
        $content = json_decode($response['content'],true);
        if (is_error($response)) {
            return false;
        }
        return $content['url'];
    }

    /**
     * @param $filesArray
     * @return bool
     * @author: 橙橙同学
     * @fun:检查提交字段
     */
    public function checkFields($filesArray){
        foreach ($filesArray as $key=>$value) {
            if(empty($value)){
                return $key.'不能为空';
            }
        }
        return true;
    }

    public function updateCardPostData($card_id){
        global $_GPC;
        $auto_activate=($_GPC['create_method']=='1')?'true':'false';
        $wx_activate=(($_GPC['create_method']=='3')||($_GPC['create_method']=='2'))?'true':'false';
        $wx_activate_url = $_GPC['wx_activate_after_submit_url'];
        $wx_activate_after_submit=($_GPC['create_method']=='3')?'true':'false';
        //卡券标题
        $title=$_GPC['title'];
        $service_phone = $_GPC['service_phone'];
        $description = $_GPC['description'];
        $quantity=$_GPC['quantity'];
        $get_limit=$_GPC['get_limit'];
        $background_pic_url=$this->doMobileWechatUploadImage($_GPC['background_pic_url']);
        $logo_url=$this->doMobileWechatUploadImage($_GPC['logo_url']);
        $prerogative = $_GPC['prerogative'];
        $custom_field1_url=$_GPC['custom_field1_url'];
        $custom_field2_url=$_GPC['custom_field2_url'];
        $custom_url_name=$_GPC['custom_url_name'];
        $custom_url=$_GPC['custom_url'];
        $custom_cell1_name=$_GPC['custom_cell1_name'];
        $custom_cell1_url=$_GPC['custom_cell1_url'];
        $promotion_url_name=$_GPC['promotion_url_name'];
        $promotion_url=$_GPC['promotion_url'];

        $post = '{
                    "card_id": "'.$card_id.'",
                    "member_card": {
                             "auto_activate":'.$auto_activate.',
                             "wx_activate":'.$wx_activate.',
                             "background_pic_url":"'.$background_pic_url.'",
                             "supply_bonus":true,
                             "supply_balance":false,
                             "prerogative":"'.$prerogative.'",  
                             "base_info": {
                              	"pay_info": 
                 				{
                         			"swipe_card":
                         			{
                            			"is_swipe_card":true
                         			}
                        		},
                                "logo_url":"'.$logo_url.'",
                                "code_type":"CODE_TYPE_QRCODE",
                                "title":"'.$title.'",
                                "color":"Color040",
                                "notice":"使用时向服务员出示此券",
                                "service_phone":"'.$service_phone.'",
                                "description":"'.$description.'",
                                "date_info":{
                                    "type":"DATE_TYPE_PERMANENT"
                                },                      
                                "get_limit":"'.$get_limit.'",
                                "can_give_friend":false,
                                "location_id_list":[
                                    477402424
                                ],
                                "custom_url_name":"'.$custom_url_name.'",
                                "custom_url":"'.$custom_url.'"
                             }
                        } 
                     }';
        return $post;
    }

    public function createCardPostData(){
        global $_GPC;
        $auto_activate=($_GPC['create_method']=='1')?'true':'false';
        $wx_activate=(($_GPC['create_method']=='3')||($_GPC['create_method']=='2'))?'true':'false';
        $wx_activate_url = $_GPC['wx_activate_after_submit_url'];
        $wx_activate_after_submit=($_GPC['create_method']=='3')?'true':'false';
        //卡券标题
        $title=$_GPC['title'];
        $service_phone = $_GPC['service_phone'];
        $description = $_GPC['description'];
        $quantity=$_GPC['quantity'];
        $get_limit=$_GPC['get_limit'];
        $brand_name=$_GPC['brand_name'];
        $background_pic_url=$this->doMobileWechatUploadImage($_GPC['background_pic_url']);
        $logo_url=$this->doMobileWechatUploadImage($_GPC['logo_url']);
        $prerogative = $_GPC['prerogative'];
        $custom_field1_url=$_GPC['custom_field1_url'];
        $custom_field2_url=$_GPC['custom_field2_url'];
        $custom_url_name=$_GPC['custom_url_name'];
        $custom_url=$_GPC['custom_url'];
        $custom_cell1_name=$_GPC['custom_cell1_name'];
        $custom_cell1_url=$_GPC['custom_cell1_url'];
        $promotion_url_name=$_GPC['promotion_url_name'];
        $promotion_url=$_GPC['promotion_url'];
        $post = '{
                  "card": {
                        "card_type": "MEMBER_CARD",
                        "member_card": {
                             "auto_activate":'.$auto_activate.',
                             "wx_activate":'.$wx_activate.',
                             "wx_activate_after_submit":'.$wx_activate_after_submit.',
                             "wx_activate_after_submit_url":"'.$wx_activate_url.'",
                             "background_pic_url":"'.$background_pic_url.'",
                             "supply_bonus":true,
                             "supply_balance":false,
                             "prerogative":"'.$prerogative.'",  
                             "base_info": {
                              	"pay_info": 
                 				{
                         			"swipe_card":
                         			{
                            			"is_swipe_card":true
                         			}
                        		},
                                "logo_url":"'.$logo_url.'",
                                "brand_name":"'.$brand_name.'", 
                                "code_type":"CODE_TYPE_QRCODE",
                                "title":"'.$title.'",
                                "color":"Color040",
                                "notice":"使用时向服务员出示此券",
                                "service_phone":"'.$service_phone.'",
                                "description":"'.$description.'",
                                "date_info":{
                                    "type":"DATE_TYPE_PERMANENT"
                                },
                                "sku":{
                                    "quantity":"'.$quantity.'"
                                },                                
                                "get_limit":"'.$get_limit.'",
                                
                                "use_custom_code":false,
                                "can_give_friend":false,
                                "location_id_list":[
                                    477402424
                                ],
                                "custom_url_name":"'.$custom_url_name.'",
                                "custom_url":"'.$custom_url.'",
                             
                                "need_push_on_view":false
                             }
                        } 
                  }
        }';
        return $post;
    }

    /**
     * @author: 橙橙同学
     * @fun:更新会员卡
     */
    public function updateWechatCard($card_id){
        global $_W;
        $post = $this->updateCardPostData($card_id);
        //更新会员卡
        $url = self::UPDATECARD.$this->getAccessToken($_W['uniacid']);
        $rest = $this->http_attach_post($url, $post);
        $resObj = json_decode($rest);
        return $resObj;
    }

    /**
     * @author:橙橙同学
     * @func:编辑会员卡页
     */
    public function doWebEditCard(){
        global $_GPC, $_W;
        load()->func('tpl');
        //获取创建卡时数据库创建的主键id
        $cardId = $_GPC['update_card_id'];
        //根据id查询创建会员卡的信息
        $row = pdo_fetch("SELECT * FROM " . tablename('wechatcard_createcard') . " 
        WHERE `id`=:cardId", array(':cardId'=>$cardId));
        include $this->template('cardmanage/edit');
    }

    /**
     * @author: 橙橙同学
     * @fun:创建保存会员卡，
     */
    public function createWechatCard(){
        global $_W;
        //准备创建会员卡数据
        $post = $this->createCardPostData();
        // 创建会员卡
        $url = self::CREATECARD.$this->getAccessToken($_W['uniacid']);
        $rest = $this->http_attach_post($url, $post);
        $resObj = json_decode($rest);
        return $resObj;
    }

    /**
     * @author: 橙橙同学
     * @fun:创建会员卡
     */
	public function doWebCreateCard() {

        load()->func('tpl');

        global $_GPC,$_W;
        if (checksubmit('submit')) {
            //检查字段合法性
            $checkFields = array('标题'=>$_GPC['title'],'激活方式'=>$_GPC['create_method'],'背景图'=>$_GPC['background_pic_url']);
            $return = $this->checkFields($checkFields);

            if(!is_bool($return)){
                message($return,'referer','error');
                exit();
            }
            //判断更新/创建
            if(!$_GPC['update_card_id']){
                //创建会员卡
                $resObj = $this->createWechatCard($_GPC,$_W);
                // 如果创建成功
                if($resObj->errcode==0){
                    // 如果为一键激活 设置开卡字段
                    $wx_activate=(($_GPC['create_method']=='3')||($_GPC['create_method']=='2'))?'true':'false';

                    if($wx_activate && $resObj->card_id){
                        $actErrRes = $this->wechatCardActivateUserform($resObj,$resObj->card_id);
                        //如果设置字段失败
                        if($actErrRes){
                            message($actErrRes, 'referer', 'error');
                            exit();
                        }
                    }

                    //记录日志
                    $data = array(
                        'title' => $_GPC['title'],
                        'create_method' => $_GPC['create_method'],
                        'create_method_name' => $this->getCreateCardMethodName($_GPC['create_method']),
                        'uniacid'=>$_W['uniacid'],
                        'card_id'=>$resObj->card_id,
                        'create_time'=>time(),
                        'cid'=>$_W['cid'],
                        'logo_url'=>$_GPC['logo_url'],
                        'brand_name'=>$_GPC['brand_name'],
                        'wx_activate_after_submit_url'=>$_GPC['wx_activate_after_submit_url'],
                        'background_pic_url'=>$_GPC['background_pic_url'],
                        'service_phone'=>$_GPC['service_phone'],
                        'prerogative'=>$_GPC['prerogative'],
                        'description'=>$_GPC['description'],
                        'custom_url_name'=>$_GPC['custom_url_name'],
                        'custom_url'=>$_GPC['custom_url'],
                        'quantity'=>$_GPC['quantity'],
                        'get_limit'=>$_GPC['get_limit']
                    );

                    $insertRes = $this->saveWechatCardCreateCard($data);
                    if($insertRes){
                        message('创建会员卡成功', 'referer', 'success');
                    }else{
                        message('创建会员卡成功 记录数据库日志失败 card_id=>'.$resObj->card_id, url('mc/wxcard/manage'), 'success');
                    }

                }else{
                    message('错误码:'.$resObj->errcode .'错误信息:'. $resObj->errmsg, 'referer', 'error');
                }
            }else{
                    //更新会员卡
                    $card_id_arr = pdo_get('wechatcard_createcard',array('id'=>$_GPC['update_card_id']),'card_id');
                    $card_id = $card_id_arr['card_id'];

                    $resObj = $this->updateWechatCard($card_id);
                    if($resObj->errcode == 0){
                        //记录日志 更新会员卡
                        $data = array(
                            'title' => $_GPC['title'],
                            'create_method' => $_GPC['create_method'],
                            'create_method_name' => $this->getCreateCardMethodName($_GPC['create_method']),
                            'uniacid'=>$_W['uniacid'],
                            'update_time'=>time(),
                            'cid'=>$_W['cid'],
                            'logo_url'=>$_GPC['logo_url'],
                            'wx_activate_after_submit_url'=>$_GPC['wx_activate_after_submit_url'],
                            'background_pic_url'=>$_GPC['background_pic_url'],
                            'service_phone'=>$_GPC['service_phone'],
                            'prerogative'=>$_GPC['prerogative'],
                            'description'=>$_GPC['description'],
                            'custom_url_name'=>$_GPC['custom_url_name'],
                            'custom_url'=>$_GPC['custom_url'],
                            'quantity'=>$_GPC['quantity'],
                            'get_limit'=>$_GPC['get_limit']
                        );
                        $updateRes = $this->updateWechatCardCreateCard($data,array('id'=>$_GPC['update_card_id']));
                        if($updateRes){
                            message('更新会员卡成功', 'referer', 'success');
                        }else{
                            message('更新会员卡成功 记录数据库日志失败 card_id=>'.$resObj->card_id, url('mc/wxcard/manage'), 'success');
                        }
                    }else{
                        message('错误码:'.$resObj->errcode .'错误信息:'. $resObj->errmsg, 'referer', 'error');
                    }

                }
        }
        include $this->template('cardmanage/createcard');
	}

    /**
     * @param $createCardMethod
     * @return string
     * @author: 橙橙同学
     * @fun:获取制作会员卡方式名称
     */
	protected function getCreateCardMethodName($createCardMethod){
	    $name = '';
	    switch ($createCardMethod){
            case 1:
                $name = '自动激活';
                break;
            case 2:
                $name = '一键激活';
                break;
            case 3:
                $name = '跳转型一键激活';
                break;
            case 4:
                $name = '接口激活';
            default:
                $name = '其它';
        }
        return $name;
    }

    /**
     * @author: 橙橙同学
     * @fun:获取微信会员卡列表
     */
    public function getWechatCardList($where = ''){
        global $_W,$_GPC;
        load()->func('tpl');
        $pindex = max(1, intval($_GPC["page"]));
        $psize = 5;
        $list = pdo_fetchall("SELECT * FROM " . tablename('wechatcard_createcard') . " 
        WHERE `uniacid`=:uniacid {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid']));
        $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('wechatcard_createcard') . " 
        WHERE uniacid = '{$_W['uniacid']}' {$where}");
        $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
        return array(
            'list'=>$list,
            'pager'=>$pager
        );
    }


	public function doWebCardManage() {
        global $_GPC, $_W;
        $op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        if($op == 'display'){

            if($_GPC['token'] == $_W['token'] && $_GPC['submit']!=''){
                //搜索
                $value = trim($_GPC['title']);
                $where = "and title like '%{$value}%'";
                $return = $this->getWechatCardList($where);

            }else{
                $return = $this->getWechatCardList();
            }
            $list = $return['list'];
            $pager = $return['pager'];
        }
        include $this->template('cardmanage/display');
	}


	public function doWebCardLog() {
		//这个操作被定义用来呈现 管理中心导航菜单
        global $_W,$_GPC;
        $op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        load()->func('tpl');
        switch ($op){
            case 'receivecard':
                //领卡日志
                $this->receiveWechatCardLog($op);
                break;
            case 'delcard':
                //删卡日志
                $this->delWechatCardLog($op);
                break;
            default:
                if($_GPC['token'] == $_W['token'] && $_GPC['submit']!=''){

                    $value = trim($_GPC['card_id']);
                    $where = "and card_id like '%{$value}%'";
                    $return = $this->getWechatCardRecordList($where);

                }else{
                    $return = $this->getWechatCardRecordList();
                }
                $list = $return['list'];
                $pager = $return['pager'];
                include $this->template('cardlog/display');
        }
	}

	public function getWechatCardStatusName($status){
        $name = '';
        switch ($status){
            case 1:
                $name = '正常';
                break;
            case 2:
                $name = '被删除';
                break;
            default:
                $name = '其它';
        }
        return $name;
    }

    public function getWechatCardRecordList($where = ''){
        global $_W,$_GPC;
        load()->func('tpl');
        $pindex = max(1, intval($_GPC["page"]));
        $psize = 5;

        $list = pdo_fetchall("SELECT * FROM " . tablename('wechatcard_record') . " 
        WHERE `uniacid`=:uniacid {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid']));

        $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('wechatcard_record') . " 
        WHERE uniacid = '{$_W['uniacid']}' {$where}");

        $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
        return array(
            'list'=>$list,
            'pager'=>$pager
        );
    }

    /**
     * @author: 橙橙同学
     * @fun:领卡日志
     */
	public function receiveWechatCardLog($op){

        include $this->template('cardlog/receivecard');
    }

    /**
     * @author: 橙橙同学
     * @fun:删卡日志
     */
    public function delWechatCardLog($op){

        include $this->template('cardlog/delcard');
    }


    public function doWebPayCard() {
        //这个操作被定义用来呈现 管理中心导航菜单

        echo '支付会员卡页面';
        include $this->template('PayCard');
    }



    public function doMobileIndexNav() {
		//这个操作被定义用来呈现 微站首页导航图标
	}
	public function doMobilePersonalNav() {
		//这个操作被定义用来呈现 微站个人中心导航
	}
	public function doMobileQkNav() {
		//这个操作被定义用来呈现 微站快捷功能导航
	}
	public function doWebSelfFun() {
		//这个操作被定义用来呈现 微站独立功能
	}


    public function http_attach_post($url, $param)
    {
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (is_string($param)) {
            $strPOST = preg_replace('/\s/', '', $param);
        } else {
            return false;
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
    public function doMobileCardEntry() {
        //这个操作被定义用来呈现 功能封面
    }

}